package iv1201project.controller;

import iv1201project.extras.Helpers;
import iv1201project.model.*;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.ejb.*;
import javax.persistence.*;

/**
 * Class for handling database-connection relating to the recruiter view.
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Stateless
public class RecruitDAO {
    
    @PersistenceContext(unitName = "IV1201ProjectPU")
    private EntityManager em;
    
    /**
     * Method for fetching an html-formatted string with applicant information.
     * @return An html-formatted string presenting applicant information.
     */
    @Logthis
    public String listApplicants() {
        String tmp = "";
        Query result = em.createNativeQuery("SELECT DISTINCT person.person_id, person.name, surname, email "
                            + "FROM person, role "
                            + "WHERE person.role_id = role.role_id AND role.role_id = 2", Person.class);
        List<Person> resultlist = result.getResultList();
        for(Person p : resultlist){
            tmp += p.getPerson_id();
            tmp += ", " + p.getSurname();
            tmp += ", " + p.getName();
            tmp += "<br />";
        }
        
        return tmp;
    }
    
    /**
     * Method for fetching person information (to be written in PDF).
     * @param i The primary key for a user in the database.
     * @return A string with the person information.
     * @throws Exception throws exception when nothing is found.
     */
    @Logthis
    public String getPersonalInfo(int i) throws Exception {
        Person person = em.find(Person.class, i);
        return person.getName();
    }
    
    /**
     * A method for creating an administrative user (recruiter) and persisting it.
     * @param recruiter The recruiter to be persisted in the database.
     */
    @Logthis
    public void addRecruiter(RecruitDTO recruiter) {
        Person person = new Person();
        
        Role role = new Role();
        role.setRole_id(1);
        
        String hashedPassword = "";
        
        try {
            hashedPassword = (new Helpers()).toSha256(recruiter.getPassword());
        } catch (NoSuchAlgorithmException ex) {
        }
        
        person.setRole_id(role);
        person.setUsername(recruiter.getUsername());
        person.setPassword(hashedPassword);
        
        em.persist(person);
    }
}
